package czy.demo.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/header")
public class HeaderController {

    private static final Logger logger = LoggerFactory.getLogger(HeaderController.class);

    /**
     * 这样可以获取所有的请求头信息,作为一个Map
     */
    @GetMapping("/all")
    public String all(@RequestHeader Map<String,String> headers){
        StringBuilder builder = new StringBuilder();
        for(Map.Entry<String,String> entry:headers.entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());
            builder.append(entry.getKey()+":"+entry.getValue()+"\n");
        }
        logger.info(builder.toString());
        return builder.toString();
    }

    /**
     * 指定名称后可以获取指定名称请求头,这个name的大小写是无所谓的
     * 默认情况下如果指定名称请求头未传递,则请求会失败,可以设置required = false
     */
    @GetMapping("/type")
    public String type(@RequestHeader(name="content-type",required = false) String contentType){
        System.out.println("获取到content-type为:"+contentType);
        return contentType;
    }

}
